<?php
namespace app\Home\controller;

// 导入控制模块
use think\Controller;

// 引入验证码信息
use think\captcha\Captcha;

// 导入Cookie
use think\Cookie;

use think\Db;

class Index extends Controller {
    // 构造函数

    public function __construct() {
        // 手动把父类的方法获取过来
        parent::__construct();

        // 在控制器的全局中保留一个全局变量
        // app/common/model/user/User.php
        $this->UserModel = model( 'User.User' );
        $this->ConfigModel = model( 'Config' );
        $this->PostModel = model( 'Post.Post' );
        $this->CommentModel = model( 'Post.Comment' );
        $this->RecordModel = model( 'User.Record' );

        $SystemList = $this->ConfigModel->select();

        $System = [];

        foreach ( $SystemList as $item ) {
            // SystemList（配置表）key当数组key
            $System[ $item[ 'key' ] ] = $item[ 'value' ];
        }
        //让每个界面都可以获取系统配置
        $this->assign( 'System', $System );
    }

    // 主页

    public function index() {

        // 获取传过来的cateid
        $cateid = $this->request->param( 'cateid', 0 );

        // 帖子状态( 全部, 未结, 已结 )
        $accept = $this->request->param( 'accept', 2 );

        // 关键字
        $keywords = $this->request->param( 'keywords', '' );

        // 查询分类列表
        $catelist = model( 'Post.Cate' )->order( 'id asc' )->limit( 6 )->select();

        $where = [];

        if ( $cateid ) {
            $where[ 'cateid' ] = $cateid;
        }

        if ( $accept < 2 ) {
            // 未结
            if ( $accept == 0 ) {
                $where[ 'accept' ] = [ 'exp', Db::raw( 'is null' ) ];
            }
            // 已结
            else {
                $where[ 'accept' ] = [ 'exp', Db::raw( 'is not null' ) ];
            }
        }

        // 关键字查询条件
        if ( $keywords ) {
            $where[ 'title|post.content' ] = [ [ 'like', "%$keywords%" ], 'OR' ];
        }

        // 查询帖子列表 查询10条
        $postlist = $this->PostModel->with( [ 'cate', 'user' ] )->where( $where )->order( 'createtime', 'desc' )->paginate( 10 );

        // 获取分页显示
        $pagestr = $postlist->render();

        // 查询所有置顶的帖子
        $postAll = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'state' => '1' ] )->order( 'createtime', 'desc' )->paginate( 4 );

        /* 判断用户今日是否签到 */
        //
        $signFlag = true;

        // 现在时间
        $nowTime = time();

        // 获取签到时间
        $signTime = date( 'Y-m-d', $nowTime );

        // 获取当前登陆用户的ID
        $userId = Cookie::get( 'LoginUser' )[ 'id' ];

        // 查找积分消费表中该用户签到的记录
        $recordList = $this->RecordModel->where( [ 'userid' => $userId, 'state' => 4 ] )->select();

        // 查询有在同一天签到的人
        foreach ( $recordList as $item ) {
            // 获取签到记录时间
            $time = date( 'Y-m-d', strtotime( $item[ 'createtime' ] ) );

            if ( $time == $signTime ) {
                $signFlag = false;
            }
        }

        /* 热议榜 */
        $hotPost = $this->PostModel->select();

        // 添加字段
        foreach ( $hotPost as $item ) {
            $item[ 'visitlen' ] = $this->PostModel->getVisitTextAttr( '', $item );
        }

        // 排序
        for ( $i = 0; $i < count( $hotPost );
        $i++ ) {
            for ( $j = $i+1; $j < count( $hotPost );
            $j++ ) {
                $temp = 0;
                if ( $hotPost[ $i ][ 'visitlen' ] < $hotPost[ $j ][ 'visitlen' ] ) {
                    $temp = $hotPost[ $i ];
                    $hotPost[ $i ] = $hotPost[ $j ];
                    $hotPost[ $j ] = $temp;
                }
            }
        }

        // 截取5条数据
        $hotPost = array_slice( $hotPost, 0, 5 );

        /* 回帖周榜 */
        $replylist = $this->CommentModel->order( 'postid' )->select();

        $postid = [];

        foreach ( $replylist as $item ) {
            $postid[] = $item[ 'postid' ];
        }

        // 通过 array_count_values() 将数组中重复的元素统计
        $reply = array_count_values( $postid );

        $postkeys = array_keys( $reply );

        $where = implode( ',', $postkeys );

        $where = '`pre_post`.`id` in('.$where.')';

        $postReplys = $this->PostModel->where( $where )->select();

        foreach ( $postReplys as $item ) {
            $item[ 'userinfo' ] = $this->UserModel->find( $item[ 'userid' ] );
        }

        // 渲染界面
        $this->assign( [
            'catelist' => $catelist,
            'cateid' => $cateid,
            'pagestr' => $pagestr,
            'postlist' => $postlist,
            'accept' => $accept,
            'postAll' => $postAll,
            'signFlag' => $signFlag,
            'hotPost' => $hotPost,
            'postReplys' => $postReplys,
            'reply' => $reply,
        ] );
        return $this->fetch();
    }

    // 登录逻辑

    public function login() {
        if ( $this->request->isPost() ) {
            // 获取输入的值
            $params = $this->request->param();

            $email = $params[ 'email' ];
            $password = $params[ 'password' ];
            $code = $params[ 'vercode' ];

            // // 判断验证码是否正确
            if ( !captcha_check( $code ) ) {
                $this->error( '验证码输入错误！' );
                exit;
            }

            // 根据邮箱查询用户信息
            $userinfo = $this->UserModel->where( [ 'email' => $email ] )->find();

            // 判断用户是否存在
            if ( !$userinfo ) {
                $this->error( '该用户不存在，请注册！' );
                exit;
            }

            // 获取用户的密码盐
            $userSalt = $userinfo[ 'salt' ];

            // 给输入的密码加密
            $password = md5( $password.$userSalt );

            if ( $password != $userinfo[ 'password' ] ) {
                $this->error( '密码错误，请重新输入！' );
                exit;
            } else {

                // 在cookie存储信息
                $data = [
                    'id' => $userinfo[ 'id' ],
                    'nickname' => $userinfo[ 'nickname' ],
                    'sex' => $userinfo[ 'sex' ],
                    'content' => $userinfo[ 'content' ],
                    'avatar' => is_file( $userinfo[ 'avatar' ] ) ? '/' . $userinfo[ 'avatar' ] : '/assets/home/images/avatar.jpg',
                    'cover' => is_file( $userinfo[ 'cover' ] ) ? '/' . $userinfo[ 'cover' ] : '/assets/home/images/back.jpg',
                    'auth' => $userinfo[ 'auth' ],
                    'vip' => $userinfo[ 'vip' ],
                    'createtime' => $userinfo[ 'createtime' ]
                ];

                Cookie::set( 'LoginUser', $data );

                $this->success( '登入成功！', url( 'home/index/index' ) );
                exit;
            }

            exit;
        }

        return $this->fetch();
    }

    // 注册逻辑

    public function register() {
        if ( $this->request->isPost() ) {

            // 获取输入的值
            $params = $this->request->param();

            $code = $this->request->param( 'vercode' );
            // 获取验证码
            $password = $params[ 'password' ];
            // 获取输入的密码
            $rePwd = $params[ 'repass' ];
            // 获取输入的确认密码
            $email = $params[ 'email' ];
            // 获取邮箱
            $name = $params[ 'nickname' ];
            // 获取昵称

            // 判断 验证码 是否正确
            if ( !captcha_check( $code ) ) {
                $this->error( '验证码输入错误！' );
                exit;
            }

            // 判断 密码 和 确认密码 是否一致
            if ( $password != $rePwd ) {
                $this->error( '密码不一致！' );
                exit;
            }

            // 生成密码盐
            $salt = randstr( 10 );

            // 密码加密
            $password = md5( $password.$salt );

            // 获取系统配置表里面的赠送积分 value 查询某个字段的值
            $RegisterPoint = $this->ConfigModel->where( [ 'key' => 'RegisterPoint' ] )->value( 'value' );

            // 判断注册积分 是不是一个整数 is_numeric() 函数用于检测变量是否为数字或数字字符。
            $RegisterPoint = is_numeric( $RegisterPoint ) ? abs( $RegisterPoint ) : 0;

            // 组装数据
            $data = [
                'email' => $email,
                'nickname' => $name,
                'password' => $password,
                'salt' => $salt,
                'point' => $RegisterPoint,
                'vip' => 0,
                'auth' => 0
            ];

            // 开始插入数据库 validate
            $res = $this->UserModel->validate( 'common/User/User' )->save( $data );

            // getLastSql() 输出查询语句
            // echo $this->UserModel->getLastSql();

            if ( $res === FALSE ) {
                // 注册失败
                // getError 返回操作的结果
                $this->error( $this->UserModel->getError() );
                exit;
            } else {
                // 注册成功，跳转到登录界面
                $this->success( '注册成功', url( 'home/index/login' ) );
                exit;
            }
            exit;

        }
        return $this->fetch();
    }

    // 生成验证码

    public function captcha() {
        $config =    [
            // 验证码位数
            'length'=> 4
        ];
        $captcha = new Captcha( $config );
        return $captcha->entry();
    }

    // 退出登录

    public function logout() {

        // 删除cookie的用户信息
        Cookie::delete( 'LoginUser' );

        // 跳转
        $this->success( '退出成功', url( 'home/index/login' ) );
        exit;
    }

    // 校验邮箱

    public function email() {
        if ( $this->request->isGet() ) {
            $email = $this->request->param( 'email', '' );

            if ( empty( $email ) ) {
                $this->error( '验证的邮箱参数有误，请重新验证！', url( 'home/user/user' ) );
                exit;
            }

            // field 查询指定字段
            $userList = $this->UserModel->field( 'id,email' )->select();

            // 定义用户id
            $id = '';

            // 获取用户的id
            foreach ( $userList as $item ) {
                $userEmail = md5( $item[ 'email' ] );
                if ( $userEmail == $email ) {
                    $id = $item[ 'id' ];
                    break;
                }
            }

            // 判断用户是否存在
            if ( empty( $id ) ) {
                $this->error( '验证的邮箱用户不存在，请重新验证！', url( 'home/user/user' ) );
                exit;
            }

            // 组转数据
            $data = [
                'id' => $id,
                'auth' => 1,
            ];

            // 使用方法修改用户的auth
            $result = $this->UserModel->isUpdate()->save( $data );

            if ( $result == false ) {
                $this->error( '邮箱校验失败！', url( 'home/user/user' ) );
                exit;
            } else {
                $this->error( '邮箱校验成功！', url( 'home/user/user' ) );
                exit;
            }

            exit;
        }
    }

    // 帖子详情页

    public function info() {
        // 分类ID
        $cateId = $this->request->param( 'cateid', 0 );

        // 查询所有的分类类列表
        $cateList = model( 'Post.Cate' )->order( 'id asc' )->limit( 6 )->select();

        // 获取帖子的ID
        $postId = $this->request->param( 'postid', 0 );

        // 获取数据库的帖子的信息
        $postInfo = $this->PostModel->with( [ 'cate', 'user' ] )->find( $postId );

        // 评论总数
        $count = $this->CommentModel->where( [ 'postid' => $postId ] )->count();

        //判断是否有登录
        $User = empty( Cookie::get( 'LoginUser' ) ) ? [] : Cookie::get( 'LoginUser' );
        $userid = isset( $User[ 'id' ] ) ? $User[ 'id' ] : 0;
        $Userinfo = $this->UserModel->find( $userid );

        //收藏的状态
        $CollectStatus = false;

        // 获取帖子表的visit信息
        $visit = trim( $postInfo[ 'visit' ] );
        // 将字符串转换为数组
        $visitArr = explode( ',', $visit );
        // 去除数组中的空元素
        $visitArr = array_filter( $visitArr );
        // is_array判断是否是个数组，count计算数组的长度
        $visitCount = is_array( $visitArr ) ? count( $visitArr ) : 0;

        if ( $Userinfo ) {
            $collect = model( 'User.Collect' )->where( [ 'userid' => $userid, 'postid' => $postId ] )->find();

            //如果查出来有，说明有收藏
            $CollectStatus = $collect ? true : false;

            //当前这个人没访问过 若 visitArr 中有用户id说明用户用户访问过这个帖子，
            if ( !in_array( $userid, $visitArr ) ) {
                $visitArr[] = $userid;

                // 组装帖子更新的信息
                $data = [
                    'id' => $postId,
                    'visit' => implode( ',', $visitArr ),
                ];

                // 更新新帖子的访问量
                $visitUpdate = $this->PostModel->isUpdate()->save( $data );
            }
        }

        // 查询评论
        $commentlist = $this->CommentModel->with( 'user' )->where( [ 'postid' => $postId ] )->order( 'id', 'asc' )->order( 'level', 'asc' )->select();

        // 将评论做递归处理
        $commentlist = CommentTree( $commentlist, 0, $Userinfo );

        /* 热议榜 */
        $hotPost = $this->PostModel->select();

        // 添加字段
        foreach ( $hotPost as $item ) {
            $item[ 'visitlen' ] = $this->PostModel->getVisitTextAttr( '', $item );
        }

        // 排序
        for ( $i = 0; $i < count( $hotPost );
        $i++ ) {
            for ( $j = $i+1; $j < count( $hotPost );
            $j++ ) {
                $temp = 0;
                if ( $hotPost[ $i ][ 'visitlen' ] < $hotPost[ $j ][ 'visitlen' ] ) {
                    $temp = $hotPost[ $i ];
                    $hotPost[ $i ] = $hotPost[ $j ];
                    $hotPost[ $j ] = $temp;
                }
            }
        }

        // 截取前10个
        $hotPost = array_slice( $hotPost, 0, 10 );

        $this->assign( [
            'catelist' => $cateList,
            'cateid' => $cateId,
            'postinfo' => $postInfo,
            'count' => $count,
            'CollectStatus'=>$CollectStatus,
            'visitCount'=>$visitCount,
            'commentlist' => $commentlist,
            'hotPost' => $hotPost
        ] );

        return $this->fetch();
    }

    // 每日签到

    public function sign() {
        // 每日积分
        $daySign = 5;

        // 提示信息
        $Tips = [
            'result' => false,
            'msg' => '',
        ];

        // 获取当前登陆用户的ID
        $userId = Cookie::get( 'LoginUser' )[ 'id' ];

        // 若没有登录，跳转到登录
        if ( !$userId ) {
            $Tips[ 'msg' ] = '请先登录！';
            return $Tips;
            exit;
        }

        // 获取用户的所有信息
        $userInfo = $this->UserModel->where( [ 'id' => $userId ] )->find();

        // 若数据库没有用户信息
        if ( !$userInfo ) {
            $Tips[ 'msg' ] = '用户不存在！';
            return $Tips;
            exit;
        }

        // 现在时间
        $nowTime = time();
        // 年月日

        // 获取签到时间
        $signTime = date( 'Y-m-d', $nowTime );

        // 查找积分消费表中该用户签到的记录
        $recordList = $this->RecordModel->where( [ 'userid' => $userId, 'state' => 4 ] )->select();

        // 查询有在同一天签到的人
        foreach ( $recordList as $item ) {
            // 获取签到记录时间
            $time = date( 'Y-m-d', strtotime( $item[ 'createtime' ] ) );
            // 年月日

            if ( $time == $signTime ) {
                $Tips[ 'msg' ] = '今日已签到过了！';
                return $Tips;
            }
        }

        /* 开启事务 */
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();

        // 获取用户的积分
        $userPoint = $userInfo[ 'point' ];

        // 用户积分操作
        $userPoint += $daySign;

        // 组装用户表信息
        $userData = [
            'id' => $userId,
            'point' => $userPoint,
        ];

        // 用户表更新
        $userRes = $this->UserModel->isUpdate()->save( $userData );

        if ( $userRes === false ) {
            $Tips[ 'msg' ] = $this->RecordModel->getError();
            return json( $Tips );
        }

        // 积分消费内容
        $recordContent = '今日签到，签到时间：'.date( 'Y-m-d H:i:s' );

        // 组装积分表数据
        $recordData = [
            'point' => $daySign,
            'content' => $recordContent,
            'state' => 4,
            'userid' => $userId,
        ];

        // 插入积分消费表
        $recordRes = $this->RecordModel->save( $recordData );

        if ( $recordRes === false ) {
            $this->UserModel->rollback();
            $Tips[ 'msg' ] = $this->RecordModel->getError();
            return json( $Tips );
        }

        // 最终判断
        if ( $userRes === false || $recordRes === false ) {
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $Tips[ 'msg' ] = '签到失败！';
            return json( $Tips );
        } else {
            // 提交事务
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $Tips[ 'result' ] = true;
            $Tips[ 'msg' ] = '签到成功！';
            return json( $Tips );
        }
    }

    // 忘记密码页

    public function forget() {
        if ( $this->request->isPost() ) {
            $email = $this->request->param( 'email', '' );
            $nickname = $this->request->param( 'nickname', '' );

            // 根据邮箱查询该用户
            $userinfo = $this->UserModel->where( [ 'email' => $email, 'nickname' => $nickname ] )->find();

            if ( !$userinfo ) {
                $this->error( '该用户不存在' );
                exit;
            }

            var_dump( $userinfo );
        }
        return $this->fetch();
    }

    // 忘记密码发送邮箱

    public function fgwemail() {
        if ( $this->request->isPost() ) {
            // 提示信息
            $success = [
                'result' => true,
                'msg' => '',
            ];

            // 拿到邮箱
            $email = $this->request->param( 'email', '' );
            $nickname = $this->request->param( 'nickname', '' );
            $code = $this->request->param( 'code', '' );

            // 组装邮箱
            if ( empty( $email ) ) {
                $success[ 'msg' ] = '邮箱不能为空！';
                return $success;
                exit;
            }

            if ( empty( $nickname ) ) {
                $success[ 'msg' ] = '昵称不能为空！';
                return $success;
                exit;
            }

            // 判断验证码是否正确
            if ( !captcha_check( $code ) ) {
                $this->error( '验证码输入错误！' );
                exit;
            }

            // 根据邮箱查询该用户
            $userinfo = $this->UserModel->where( [ 'email' => $email, 'nickname' => $nickname ] )->find();

            if ( !$userinfo ) {
                $success[ 'msg' ] = '邮箱或昵称错误！';
                return $success;
                exit;
            }

            // 邮箱加密
            $emails = md5( $email );

            // 组装信息
            $msg = "<a href='http://www.thinkphp.com/home/index/repwd?email=$emails'>点击修改密码</a>";

            // 调用公共函数库里面的发送方法
            $result = send( $email, $msg );

            if ( $result ) {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '邮箱发送成功！';
            } else {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = '邮箱发送失败！';
            }

            return $success;

        }
        exit;
    }

    // 忘记密码修改密码

    public function repwd() {
        $email = $this->request->param( 'email', '' );

        //
        if ( $this->request->isGet() ) {

            // 判断邮箱是否为空
            if ( empty( $email ) ) {
                $this->error( '请先登录', url( 'home/index/login' ) );
                exit;
            }

            $userList = $this->UserModel->field( 'id,email' )->select();

            // 定义用户id
            $id = '';

            // 获取用户的id
            foreach ( $userList as $item ) {
                $userEmail = md5( $item[ 'email' ] );
                if ( $userEmail == $email ) {
                    $id = $item[ 'id' ];
                    break;
                }
            }

            if ( empty( $id ) ) {
                $this->error( '用户不存在，前往注册', url( 'home/index/register' ) );
                exit;
            }

            $this->assign( [
                'email' => $email,
            ] );

            return $this->fetch();
        }

        // 表单
        if ( $this->request->isPost() ) {
            // 提示信息
            $success = [
                'result' => true,
                'msg' => '',
            ];

            $newpwd = $this->request->param( 'password', '' );
            $oldpwd = $this->request->param( 'repassword', '' );
            $code = $this->request->param( 'code', '' );
            $Uemail = $this->request->param( 'email', '' );

            // 判断验证码是否正确
            // if ( !captcha_check( $code ) ) {
            //     $success[ 'msg' ] = '验证码！请重新输入';
            //     return $success;
            //     exit;
            // }

            // 判断密码是否一致
            if ( $newpwd != $oldpwd ) {
                $success[ 'msg' ] = '密码不一致！请重新输入';
                return $success;
                exit;
            }

            $userList = $this->UserModel->field( 'id,email' )->select();

            // 定义用户id
            $userid = '';

            // 获取用户的id
            foreach ( $userList as $item ) {
                $userEmail = md5( $item[ 'email' ] );
                if ( $userEmail == $Uemail ) {
                    $userid = $item[ 'id' ];
                    break;
                }
            }

            if ( empty( $userid ) ) {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '用户不存在';
                $success[ 'url' ] = 'register';
                return $success;
                exit;
            }

            // 生成密码盐
            $salt = randstr( 10 );

            // 密码加密
            $newpwd = md5( $newpwd.$salt );

            $data = [
                'id' => $userid,
                'salt' => $salt,
                'password' => $newpwd,
            ];

            // 更新数据
            $result = $this->UserModel->isUpdate()->save( $data );

            if ( $result === FALSE ) {
                //修改失败$this->UserModel->getError()
                $success[ 'msg' ] = $this->UserModel->getError() ;
                return $success;
                exit;
            } else {
                //修改成功
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '修改密码成功！' ;
                $success[ 'url' ] =  'login';
                return $success;
                exit;
            }

            return $newpwd;

        }

    }
}
